package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDto;
import com.heima.model.user.pojo.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.util.HashMap;
import java.util.Map;

@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户登录功能
     * @param loginDto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //判断接收参数是否为空
        String phone = loginDto.getPhone();
        if (StringUtils.isNotEmpty(loginDto.getPassword()) && StringUtils.isNotEmpty(phone)) {


            //不为空先根据手机号查询数据库
            LambdaQueryWrapper<ApUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApUser::getPhone, phone);
            ApUser user = this.getOne(queryWrapper);
            //对查询的user对象进行判断
            if (user == null) {
                //如果对象为空,则返回错误信息
                return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //如果不为空,则进行密码校验
            //先查询出salt
            String salt = user.getSalt();
            //拼接密码,并进行MD5加密
            String password = DigestUtils.md5DigestAsHex((salt + loginDto.getPassword()).getBytes());
            //与数据库存的密码进行比对
            if (!password.equals(user.getPassword())) {
                //不一致返回错误信息
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //一致则生成token令牌
            String token = AppJwtUtil.getToken(user.getId().longValue());
            //将user信息以及token封装成map进行返回
            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            //封装user之前先将敏感信息隐藏
            user.setPassword(null);
            user.setSalt(null);
            map.put("user", user);
            return ResponseResult.okResult(map);
        }
        //为空则为游客方式登录
        String token = AppJwtUtil.getToken(0L);
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}
